let axios = require("axios").default
let querystring = require("querystring")
let {genRandomStr} = require("./helper")
axios.defaults.baseURL = "https://api.weixin.qq.com/"
let hasOwnProperty = Object.prototype.hasOwnProperty

class WxApi {
	static init() {
		this.apiMap = new Map()
	}

	constructor({appid, secret}) {
		this.appid = appid
		this.secret = secret
		this.instance = axios.create({
		})
		this.token = undefined
		this.instance.interceptors.response.use(
			response => {
				if (response.data.errcode != undefined && response.data.errcode != 0) {
					let e = new Error("wechat can't respone")
					e.data = response.data
					throw e
				}
				return response
			},
			error => {

			}
		)
		this.instance.interceptors.request.use(async (req) => {
			if (hasOwnProperty.call(req.params, "access_token") && req.params.access_token === undefined) { // hOwnpro
				// await axios.get()
				await getAccessToken()
				req.params.access_token = this.token
			}
		}, function (error) {
			console.log(error)
		})
	}
	/**
	 * @returns {WxApi} param0 
	 */
	static getInstance({appid, secret}) {
		let wxApi = this.apiMap.get(JSON.stringify({appid, secret}))
		if (wxApi) {
			return wxApi
		} else {
			wxApi = new WxApi({appid, secret})
			this.apiMap.set(JSON.stringify({appid, secret}))
		}
		return wxApi
	}

	async getAccessToken() {
		let token = (await axios.get("/cgi-bin/token", {
			params: {
				grant_type: "client_credential",
				appid: this.appid,
				secret: this.secret
			}
		})).data.access_token
		if (!token) {
			throw new Error("")
		}
		this.token = token
		return true
	}

	async  getCode2({appid, secret, js_code, grant_type = "authorization_code"}) {
		let data = (await axios.get("/sns/jscode2session", {params: {appid: this.appid, secret: this.secret, js_code, grant_type}})).data
		return data
	}

	async sendTemplate() {
		let data = (await this.instance.post("/cgi-bin/message/wxopen/template/send", JSON.stringify(

		),
		{
			params: {
				access_token: this.token
			}
		})).data
		return data
	}

	async getTemplate({
		offset = 0,
		count = 20
	}) {
		let data = (this.instance.post("/cgi-bin/wxopen/template/list", JSON.stringify({
			offset, count
		}),
		{
			params: {
				access_token: this.token
			}
		})).then(console.log)
		return data
	}
}
WxApi.init()
// require("../util/wechat").PromWxApi();
module.exports = {WxApi}

// WxApi.

WxApi.getInstance({appid: "wxcc5fe7496a53b97d", secret: "badc275e86b3c2efd0c49485f5851db0"}).getTemplate({}).then(console.log)